package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.property.dao.*;
import com.itlong.cloud.property.service.IDeviceMediaInfoService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 * 设备多媒体信息处理接口实现.
 * </desc>
 *
 * @createDate 2017-10-19
 */
@Service
public class DeviceMediaInfoServiceImpl  implements IDeviceMediaInfoService {

    @Autowired
    private IDeviceMediaInfoDao iDeviceMediaInfoDao; //设备多媒体信息数据库访问对象

    @Autowired
    private IDeviceMediaWallDao iDeviceMediaWallDao; //围墙机设备多媒体服务信息数据库访问对象

    @Autowired
    private IDeviceMediaGateDao iDeviceMediaGateDao; //门口机设备多媒体服务信息数据库访问对象

    @Autowired
    private IDeviceCloudIntercomBridgeInfoDao iDeviceCloudIntercomBridgeInfoDao; // 云对讲归属地信息数据库访问对象

    @Autowired
    private IDeviceMediaPadFaceDao iDeviceMediaPadFaceDao;  //平板人脸识别多媒体服务设备信息持久层对象

    @Autowired
    private MessageSender messageSender; //RabitMQ发送
    /**
     * <desc>
     *      一键启用/禁用设备多媒体多媒体
     * </desc>
     *
     * @param deviceMediaSetEnableDTO  一键启用/禁用多媒体信息参数对象
     * @return 受影响的行数
     * @author Lix
     * @createDate 2017-10-23
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer setMediaInfoEnable(DeviceMediaSetEnableDTO deviceMediaSetEnableDTO) throws Exception {

        //一键启用/禁用设备多媒体多媒体更新到数据库（事务保护）
        Integer intRes =  this.setMediaInfoEnableToDB(deviceMediaSetEnableDTO);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("projectId",deviceMediaSetEnableDTO.getProjectId());
        DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_MEDIA,jsonObject,deviceMediaSetEnableDTO.getProjectId());
        List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS = new ArrayList<>();
        deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
        JSONObject dataJs = new JSONObject();
        dataJs.put("data",deviceBusinessChangeLogPOS);
        messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);
        // 云门禁
        List<DeviceBusinessEntranceChangeLogPO> changeEntranceLogPOS = new ArrayList<>();
        changeEntranceLogPOS.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_MEDIA, jsonObject, deviceMediaSetEnableDTO.getProjectId()));
        JSONObject dataJsEntrance = new JSONObject();
        dataJsEntrance.put("data", changeEntranceLogPOS);
        //发送云门禁指令
        messageSender.send(
                RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                JSON.toJSONString(dataJsEntrance),
                RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
        );

        return intRes;
    }


    /**
     * <desc>
     *      一键启用/禁用设备多媒体多媒体
     * </desc>
     *
     * @param deviceMediaSetEnableDTO  一键启用/禁用多媒体信息参数对象
     * @return 受影响的行数
     * @author LewisLouis
     * @createDate 2018-02-25
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer setMediaInfoEnableToDB(DeviceMediaSetEnableDTO deviceMediaSetEnableDTO) throws Exception {
        List<String> mediaIdList = Arrays.asList(deviceMediaSetEnableDTO.getMediaIds().split(","));
        Integer intRes =  iDeviceMediaInfoDao.setMediaInfoEnable(deviceMediaSetEnableDTO.getMediaStatus(),deviceMediaSetEnableDTO.getEnabled(),mediaIdList);
        return intRes;
    }

    /**
     * <desc>
     *      分页查询设备多媒体信息
     * </desc>
     *
     * @param deviceMediaInfoGetPageDTO  设备多媒体信息数据传输对象
     * @return  分页查询结果列表
     * @author Lix
     * @createDate 2017-10-23
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<DeviceMediaInfoVO> getMediaInfoByPage(DeviceMediaInfoGetPageDTO deviceMediaInfoGetPageDTO) throws Exception {
        if (StringUtils.isBlank(deviceMediaInfoGetPageDTO.getOrderColumn()) || StringUtils.isBlank(deviceMediaInfoGetPageDTO.getOrderRule())){
            deviceMediaInfoGetPageDTO.setOrderColumn("createTime");
            deviceMediaInfoGetPageDTO.setOrderRule("DESC");
        }
        //将DTO转换为Map params
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(deviceMediaInfoGetPageDTO);
        params.put("projectId", deviceMediaInfoGetPageDTO.getProjectId());

        Page<DeviceMediaInfoVO> page = new Page<>();
        page.getPage().setPageSize(deviceMediaInfoGetPageDTO.getPageSize());
        page.getPage().setCurrentPage(deviceMediaInfoGetPageDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        //填充返回数据集
        List<DeviceMediaInfoVO> datas = iDeviceMediaInfoDao.getDeviceMediaInfoByPage(params);
        page.setRows(datas, iDeviceMediaInfoDao.getRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      保存单个多媒体资源
     * </desc>
     *
     * @param deviceMediaInfoSaveDTO 保存多媒体资源数据传输对象
     * @return 受影响的行数
     * @throws Exception
     * @author wangzhi
     * @createDate 2018-3-28
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer saveDeviceMediaInfo(DeviceMediaInfoSaveDTO deviceMediaInfoSaveDTO) throws Exception {
        String mediaId = LogicIdUtil.bussinessId();
        Date saveTime = new Date();
        //保存设备多媒体信息
        DeviceMediaInfoPO deviceMediaInfoPO = new DeviceMediaInfoPO();
        deviceMediaInfoPO.setMediaId(mediaId);
        BeanUtils.copyProperties(deviceMediaInfoSaveDTO,deviceMediaInfoPO);
        deviceMediaInfoPO.setAttacheFile(deviceMediaInfoSaveDTO.getAttacheFiles());
        deviceMediaInfoPO.setAttacheFileUrl(deviceMediaInfoSaveDTO.getAttacheFileUrls());
        deviceMediaInfoPO.setCreateTime(saveTime);
        deviceMediaInfoPO.setUpdateTime(saveTime);

        //保存多媒体信息到数据库（事务保护）
        int intRes = this.saveDeviceMediaInfo2DB(deviceMediaInfoPO,deviceMediaInfoSaveDTO);

        //仅多媒体资源添加时设备类型为云对讲、状态为启用且发布状态为已发布时才通知云对讲更新
        if (NumberHandlerUtil.isEqual(deviceMediaInfoPO.getStatus(),DataStatusEnum.NORMAL.getType()) &&
                NumberHandlerUtil.isEqual(deviceMediaInfoPO.getPublishStatus(),DeviceMediaInfoPublishStatusEnum.PUBLISHED.getType())){
            if (NumberHandlerUtil.isEqual(deviceMediaInfoPO.getEquipType(),PropertyEquipTypeEnum.CLOUD_INTERCOM.getType())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("projectId",deviceMediaInfoSaveDTO.getProjectId());
                DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                        = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_MEDIA,jsonObject,deviceMediaInfoSaveDTO.getProjectId());
                List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS = new ArrayList<>();
                deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
                JSONObject dataJs = new JSONObject();
                dataJs.put("data",deviceBusinessChangeLogPOS);
                messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                        JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);
            }
            if (NumberHandlerUtil.isEqual(deviceMediaInfoPO.getEquipType(),PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("projectId",deviceMediaInfoSaveDTO.getProjectId());
                // 云门禁
                List<DeviceBusinessEntranceChangeLogPO> changeEntranceLogPOS = new ArrayList<>();
                changeEntranceLogPOS.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_MEDIA, jsonObject, deviceMediaInfoSaveDTO.getProjectId()));
                JSONObject dataJs = new JSONObject();
                dataJs.put("data", changeEntranceLogPOS);
                //发送云门禁指令
                messageSender.send(
                        RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                        JSON.toJSONString(dataJs),
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
                );
            }
        }
        return intRes;
    }

    /**
     * <desc>
     *     保存多媒体资源
     * </desc>
     *
     * @param deviceMediaInfoPO 多媒体资源实体类对象
     * @param deviceMediaInfoSaveDTO 多媒体资源保存传输对象
     * @return 受影响的总行数
     * @throws Exception
     * @author wangzhi
     * @createDate 2018-3-28
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer saveDeviceMediaInfo2DB(DeviceMediaInfoPO deviceMediaInfoPO,DeviceMediaInfoSaveDTO deviceMediaInfoSaveDTO) throws Exception{
        iDeviceMediaInfoDao.save(SqlUtil.durableData(deviceMediaInfoPO, PlatformConstants.TABLE_SAVE));
        int intRes = 0;
        List<Map<String,Object>> batchParams = new ArrayList<>();
        if (!(null == deviceMediaInfoSaveDTO.getBindDeviceInfo() || deviceMediaInfoSaveDTO.getBindDeviceInfo().isEmpty())) {
            //批量保存围墙机多媒体资源-围墙机关联信息
            for (DeviceMediaBindDeviceDTO deviceMediaBindDeviceDTO:deviceMediaInfoSaveDTO.getBindDeviceInfo()){
                DeviceMediaWallPO deviceMediaWallPO = new DeviceMediaWallPO();
                deviceMediaWallPO.setMediaId(deviceMediaInfoPO.getMediaId());
                deviceMediaWallPO.setProjectId(deviceMediaInfoSaveDTO.getProjectId());
                deviceMediaWallPO.setDeviceUnique(deviceMediaBindDeviceDTO.getDeviceUnique());
                deviceMediaWallPO.setSn(deviceMediaBindDeviceDTO.getSn());
                deviceMediaWallPO.setCreateTime(deviceMediaInfoPO.getCreateTime());
                deviceMediaWallPO.setUpdateTime(deviceMediaInfoPO.getCreateTime());
                deviceMediaWallPO.setStatus(DataStatusEnum.NORMAL.getType());
                batchParams.add(SqlUtil.durableData(deviceMediaWallPO, PlatformConstants.TABLE_SAVE));
            }
            //保存围墙机关联信息
            intRes += iDeviceMediaWallDao.batchSave(batchParams);
        }

        if (!(null == deviceMediaInfoSaveDTO.getBindAddressInfo() || deviceMediaInfoSaveDTO.getBindAddressInfo().isEmpty())){
            //批量保存门口机多媒体资源-服务地址关联信息
            batchParams.clear();
            for (DeviceMediaBindAddressDTO deviceMediaBindAddressDTO:deviceMediaInfoSaveDTO.getBindAddressInfo()) {
                DeviceMediaGatePO deviceMediaGatePO = new DeviceMediaGatePO();
                deviceMediaGatePO.setMediaId(deviceMediaInfoPO.getMediaId());
                deviceMediaGatePO.setProjectId(deviceMediaInfoSaveDTO.getProjectId());
                deviceMediaGatePO.setDeviceUnique(deviceMediaBindAddressDTO.getDeviceUnique());
                deviceMediaGatePO.setCreateTime(deviceMediaInfoPO.getCreateTime());
                deviceMediaGatePO.setUpdateTime(deviceMediaInfoPO.getCreateTime());
                deviceMediaGatePO.setStatus(DataStatusEnum.NORMAL.getType());
                batchParams.add(SqlUtil.durableData(deviceMediaGatePO, PlatformConstants.TABLE_SAVE));
            }
            intRes +=  iDeviceMediaGateDao.batchSave(batchParams);
        }

        if (null != deviceMediaInfoSaveDTO.getBindPadFaceInfo() && !deviceMediaInfoSaveDTO.getBindPadFaceInfo().isEmpty()){
            // 批量保存多媒体资源-人脸识别设备关联信息
            batchParams.clear();
            for (DeviceMediaBindPadFaceDTO deviceMediaBindPadFaceDTO:deviceMediaInfoSaveDTO.getBindPadFaceInfo()){
                DeviceMediaPadFaceRecognitionPO deviceMediaPadFaceRecognitionPO = new DeviceMediaPadFaceRecognitionPO();
                deviceMediaPadFaceRecognitionPO.setMediaId(deviceMediaInfoPO.getMediaId());
                deviceMediaPadFaceRecognitionPO.setProjectId(deviceMediaInfoSaveDTO.getProjectId());
                deviceMediaPadFaceRecognitionPO.setDeviceUnique(deviceMediaBindPadFaceDTO.getDeviceUnique());
                deviceMediaPadFaceRecognitionPO.setCreateTime(deviceMediaInfoPO.getCreateTime());
                deviceMediaPadFaceRecognitionPO.setUpdateTime(deviceMediaInfoPO.getCreateTime());
                deviceMediaPadFaceRecognitionPO.setStatus(DataStatusEnum.NORMAL.getType());
                batchParams.add(SqlUtil.durableData(deviceMediaPadFaceRecognitionPO,PlatformConstants.TABLE_SAVE));
            }
            intRes += iDeviceMediaPadFaceDao.batchSave(batchParams);
        }

        if (null != deviceMediaInfoSaveDTO.getBindUnibodyEntranceInfo() && !deviceMediaInfoSaveDTO.getBindUnibodyEntranceInfo().isEmpty()){
            // 批量保存多媒体资源-一体式人脸识别门禁设备关联信息
            batchParams.clear();
            for (DeviceMediaBindPadFaceDTO deviceMediaBindPadFaceDTO:deviceMediaInfoSaveDTO.getBindUnibodyEntranceInfo()){
                DeviceMediaEntrancePO deviceMediaEntrancePO = new DeviceMediaEntrancePO();
                deviceMediaEntrancePO.setMediaId(deviceMediaInfoPO.getMediaId());
                deviceMediaEntrancePO.setProjectId(deviceMediaInfoSaveDTO.getProjectId());
                deviceMediaEntrancePO.setDeviceUnique(deviceMediaBindPadFaceDTO.getDeviceUnique());
                deviceMediaEntrancePO.setCreateTime(deviceMediaInfoPO.getCreateTime());
                deviceMediaEntrancePO.setUpdateTime(deviceMediaInfoPO.getCreateTime());
                deviceMediaEntrancePO.setStatus(DataStatusEnum.NORMAL.getType());
                batchParams.add(SqlUtil.durableData(deviceMediaEntrancePO,PlatformConstants.TABLE_SAVE));
            }
            intRes += iDeviceMediaGateDao.batchSaveEntrance(batchParams);
        }

        return intRes;
    }

    /**
     * <desc>
     *      获取单个设备多媒体信息
     * </desc>
     *
     * @param mediaId 多媒体id
     * @return 单个设备多媒体信息结果对象
     * @author wangzhi
     * @createDate 2018-03-28
     */
    @Override
    public DeviceMediaInfoGetVO getOneMediaInfo(String mediaId) {

        DeviceMediaInfoVO mediaInfoVO = iDeviceMediaInfoDao.getOneMediaInfo(mediaId);
        if (mediaInfoVO == null){
            return  null;
        }
        DeviceMediaInfoGetVO deviceMediaInfoGetVO = new DeviceMediaInfoGetVO();
        BeanUtils.copyProperties(mediaInfoVO, deviceMediaInfoGetVO);

        List<DeviceMediaAttacheFileInfoVO> deviceMediaAttacheFileInfoVOS = new ArrayList<>();
        List<String> attacheFileUrls = castStrToListByCommaChar(mediaInfoVO.getAttacheFileUrl());
        List<String> attacheFileNames = castStrToListByCommaChar(mediaInfoVO.getAttacheFile());
        List<String> attacheFileMd5s = castStrToListByCommaChar(mediaInfoVO.getAttacheFileMd5());

        for (int fileIndex = 0; fileIndex< attacheFileUrls.size();fileIndex++){
            DeviceMediaAttacheFileInfoVO deviceMediaAttacheFileInfoVO = new DeviceMediaAttacheFileInfoVO();
            if (attacheFileNames.size() > fileIndex) {
                String fileName = attacheFileNames.get(fileIndex);
                deviceMediaAttacheFileInfoVO.setFileName(fileName);
            }
            if (attacheFileUrls.size() > fileIndex){
                deviceMediaAttacheFileInfoVO.setAttacheFileUrl(attacheFileUrls.get(fileIndex));
            }
            if (attacheFileMd5s.size() > fileIndex){
                deviceMediaAttacheFileInfoVO.setFileMd5(attacheFileMd5s.get(fileIndex));
            }
            deviceMediaAttacheFileInfoVOS.add(deviceMediaAttacheFileInfoVO);
        }
        deviceMediaInfoGetVO.setAttacheFiles(deviceMediaAttacheFileInfoVOS);

        List<DeviceMediaBindInfosVO> bindInfos = new ArrayList<>();

        // 分情况获取绑定的平板人脸识别设备列表
        if (NumberHandlerUtil.isEqual(deviceMediaInfoGetVO.getChildrenType(),PropertyEquipTypeEnum.CLOUD_ELEVATOR.getType())){
            List<DeviceMediaBindAddressVO> deviceMediaBindCloudElevators = iDeviceMediaPadFaceDao.getMediaBindCloudElevators(mediaId);
            if (null != deviceMediaBindCloudElevators && !deviceMediaBindCloudElevators.isEmpty()){
                for (DeviceMediaBindAddressVO deviceMediaBindDeviceVO:deviceMediaBindCloudElevators){
                    DeviceMediaBindInfosVO deviceMediaBindInfosVO = new DeviceMediaBindInfosVO();
                    BeanUtils.copyProperties(deviceMediaBindDeviceVO,deviceMediaBindInfosVO);
                    bindInfos.add(deviceMediaBindInfosVO);
                }
            }
            deviceMediaInfoGetVO.setBindInfos(bindInfos);
            return deviceMediaInfoGetVO;
        } else if (NumberHandlerUtil.isEqual(deviceMediaInfoGetVO.getChildrenType(),PropertyEquipTypeEnum.ENTRANCE.getType())){
            List<DeviceMediaBindAddressVO> deviceMediaBindCloudEntrances = iDeviceMediaPadFaceDao.getMediaBindCloudEntrance(mediaId);
            if (null != deviceMediaBindCloudEntrances && !deviceMediaBindCloudEntrances.isEmpty()){
                for (DeviceMediaBindAddressVO deviceMediaBindAddressVO:deviceMediaBindCloudEntrances){
                    DeviceMediaBindInfosVO deviceMediaBindInfosVO = new DeviceMediaBindInfosVO();
                    BeanUtils.copyProperties(deviceMediaBindAddressVO,deviceMediaBindInfosVO);
                    bindInfos.add(deviceMediaBindInfosVO);
                }
            }
            deviceMediaInfoGetVO.setBindInfos(bindInfos);
            return deviceMediaInfoGetVO;
        } else if (NumberHandlerUtil.isEqual(deviceMediaInfoGetVO.getEquipType(),PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType())){
            List<DeviceMediaBindAddressVO> deviceMediaBindCloudEntrances = iDeviceMediaPadFaceDao.getMediaBindCloudUnibodyEntrance(mediaId);
            if (null != deviceMediaBindCloudEntrances && !deviceMediaBindCloudEntrances.isEmpty()){
                for (DeviceMediaBindAddressVO deviceMediaBindAddressVO:deviceMediaBindCloudEntrances){
                    DeviceMediaBindInfosVO deviceMediaBindInfosVO = new DeviceMediaBindInfosVO();
                    BeanUtils.copyProperties(deviceMediaBindAddressVO,deviceMediaBindInfosVO);
                    bindInfos.add(deviceMediaBindInfosVO);
                }
            }
            deviceMediaInfoGetVO.setBindInfos(bindInfos);
            return deviceMediaInfoGetVO;
        }

        // 获取绑定的地址信息
        List<DeviceMediaBindAddressVO> deviceMediaBindAddressVOList = iDeviceMediaGateDao.getOneMediaGateInfo(mediaId);
        if (null != deviceMediaBindAddressVOList && !deviceMediaBindAddressVOList.isEmpty()){
            for(DeviceMediaBindAddressVO deviceMediaBindAddressVO:deviceMediaBindAddressVOList){
                DeviceMediaBindInfosVO deviceMediaBindInfosVO = new DeviceMediaBindInfosVO();
                deviceMediaBindInfosVO.setSmartType(31);
                BeanUtils.copyProperties(deviceMediaBindAddressVO,deviceMediaBindInfosVO);
                bindInfos.add(deviceMediaBindInfosVO);
            }
        }

        // 获取绑定的围墙机信息
        List<DeviceMediaBindDeviceVO> deviceMediaBindDeviceVOS = iDeviceMediaWallDao.getOneMediaWallInfo(mediaId);
        if (null != deviceMediaBindDeviceVOS && !deviceMediaBindDeviceVOS.isEmpty()){
            for (DeviceMediaBindDeviceVO deviceMediaBindDeviceVO:deviceMediaBindDeviceVOS){
                DeviceMediaBindInfosVO deviceMediaBindInfosVO = new DeviceMediaBindInfosVO();
                deviceMediaBindInfosVO.setSmartType(32);
                BeanUtils.copyProperties(deviceMediaBindDeviceVO,deviceMediaBindInfosVO);
                bindInfos.add(deviceMediaBindInfosVO);
            }
        }
        // 将绑定信息添加到返回值中
        deviceMediaInfoGetVO.setBindInfos(bindInfos);

        return deviceMediaInfoGetVO;
    }

    /**
     * <desc>
     *      修改单个多媒体资源
     * </desc>
     *
     * @param deviceMediaInfoUpdateDTO 修改多媒体资源数据传输对象
     * @return 受影响的行数
     * @throws Exception
     * @author wangzhi
     * @createDate 2018-3-28
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer updateDeviceMediaInfo(DeviceMediaInfoUpdateDTO deviceMediaInfoUpdateDTO) throws Exception {

        Date updateTime = new Date();
        //保存设备多媒体信息
        DeviceMediaInfoPO deviceMediaInfoPO = new DeviceMediaInfoPO();
        BeanUtils.copyProperties(deviceMediaInfoUpdateDTO,deviceMediaInfoPO);
        deviceMediaInfoPO.setAttacheFile(deviceMediaInfoUpdateDTO.getAttacheFiles());
        deviceMediaInfoPO.setAttacheFileUrl(deviceMediaInfoUpdateDTO.getAttacheFileUrls());
        deviceMediaInfoPO.setProjectId(null);
        deviceMediaInfoPO.setUpdateTime(updateTime);

        //修改设备多媒体信息(事务保护)
        Integer intRes = this.updateDeviceMediaInfo2DB(deviceMediaInfoPO,deviceMediaInfoUpdateDTO);

        // 若设备类型为平板人脸识别，则不需要发送消息队列通知更新
        if (NumberHandlerUtil.isEqual(deviceMediaInfoUpdateDTO.getEquipType(),PropertyEquipTypeEnum.PAD_FACE_RECOGNITION.getType())){
            return intRes;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("projectId",deviceMediaInfoUpdateDTO.getProjectId());
        DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_MEDIA,jsonObject,deviceMediaInfoUpdateDTO.getProjectId());
        List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS = new ArrayList<>();
        deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
        JSONObject dataJs = new JSONObject();
        dataJs.put("data",deviceBusinessChangeLogPOS);
        messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);

        if (null != deviceMediaInfoUpdateDTO.getBindUnibodyEntranceInfo() && !deviceMediaInfoUpdateDTO.getBindUnibodyEntranceInfo().isEmpty()) {
            // 云门禁
            List<DeviceBusinessEntranceChangeLogPO> changeEntranceLogPOS = new ArrayList<>();
            changeEntranceLogPOS.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_MEDIA, jsonObject, deviceMediaInfoUpdateDTO.getProjectId()));
            dataJs.put("data", changeEntranceLogPOS);
            //发送云门禁指令
            messageSender.send(
                    RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                    JSON.toJSONString(dataJs),
                    RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
            );
        }

        return  intRes;
    }

    /**
     * <desc>
     *     保存多媒体资源
     * </desc>
     *
     * @param deviceMediaInfoPO 多媒体资源实体类对象
     * @param deviceMediaInfoUpdateDTO 多媒体资源修改传输对象
     * @return 受影响的总行数
     * @throws Exception
     * @author wangzhi
     * @createDate 2018-3-28
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer updateDeviceMediaInfo2DB(DeviceMediaInfoPO deviceMediaInfoPO,DeviceMediaInfoUpdateDTO deviceMediaInfoUpdateDTO) throws Exception{

        // 先修改多媒体资源基本信息表
        iDeviceMediaInfoDao.update(SqlUtil.durableData(deviceMediaInfoPO, PlatformConstants.TABLE_UPDATE));
        int intRes = 0;
        List<Map<String,Object>> batchParams = new ArrayList<>();

        // 设备类型为平板人脸识别时，处理绑定平板人脸识别设备修改业务
        if (NumberHandlerUtil.isEqual(deviceMediaInfoUpdateDTO.getEquipType(),PropertyEquipTypeEnum.PAD_FACE_RECOGNITION.getType())){
            iDeviceMediaPadFaceDao.removeOne(deviceMediaInfoUpdateDTO.getMediaId());
            if (null != deviceMediaInfoUpdateDTO.getBindPadFaceInfo() && !deviceMediaInfoUpdateDTO.getBindPadFaceInfo().isEmpty()){
                batchParams.clear();
                for (DeviceMediaBindPadFaceDTO deviceMediaBindPadFaceDTO:deviceMediaInfoUpdateDTO.getBindPadFaceInfo()){
                    DeviceMediaPadFaceRecognitionPO deviceMediaPadFaceRecognitionPO = new DeviceMediaPadFaceRecognitionPO();
                    deviceMediaPadFaceRecognitionPO.setMediaId(deviceMediaInfoUpdateDTO.getMediaId());
                    deviceMediaPadFaceRecognitionPO.setProjectId(deviceMediaInfoUpdateDTO.getProjectId());
                    deviceMediaPadFaceRecognitionPO.setDeviceUnique(deviceMediaBindPadFaceDTO.getDeviceUnique());
                    deviceMediaPadFaceRecognitionPO.setStatus(DataStatusEnum.NORMAL.getType());
                    deviceMediaPadFaceRecognitionPO.setCreateTime(deviceMediaInfoPO.getUpdateTime());
                    deviceMediaPadFaceRecognitionPO.setUpdateTime(deviceMediaInfoPO.getUpdateTime());
                    batchParams.add(SqlUtil.durableData(deviceMediaPadFaceRecognitionPO,PlatformConstants.TABLE_SAVE));
                }
                // 保存关联信息
                intRes += iDeviceMediaPadFaceDao.batchSave(batchParams);
            }
            return intRes;
        }

        //先删除原来的所有多媒体资源-围墙机设备关系
        iDeviceMediaWallDao.removeOne(deviceMediaInfoUpdateDTO.getMediaId());
        if (!(null == deviceMediaInfoUpdateDTO.getBindDeviceInfo() || deviceMediaInfoUpdateDTO.getBindDeviceInfo().isEmpty())) {
            batchParams.clear();
            for (DeviceMediaBindDeviceDTO deviceMediaBindDeviceDTO:deviceMediaInfoUpdateDTO.getBindDeviceInfo()){
                DeviceMediaWallPO deviceMediaWallPO = new DeviceMediaWallPO();
                deviceMediaWallPO.setMediaId(deviceMediaInfoUpdateDTO.getMediaId());
                deviceMediaWallPO.setProjectId(deviceMediaInfoUpdateDTO.getProjectId());
                deviceMediaWallPO.setDeviceUnique(deviceMediaBindDeviceDTO.getDeviceUnique());
                deviceMediaWallPO.setSn(deviceMediaBindDeviceDTO.getSn());
                deviceMediaWallPO.setCreateTime(deviceMediaInfoPO.getUpdateTime());
                deviceMediaWallPO.setUpdateTime(deviceMediaInfoPO.getUpdateTime());
                deviceMediaWallPO.setStatus(DataStatusEnum.NORMAL.getType());
                batchParams.add(SqlUtil.durableData(deviceMediaWallPO, PlatformConstants.TABLE_SAVE));
            }
            //保存围墙机关联信息
            intRes += iDeviceMediaWallDao.batchSave(batchParams);
        }

        //修改门口机关联信息
        iDeviceMediaGateDao.removeOne(deviceMediaInfoUpdateDTO.getMediaId());
        if (!(null == deviceMediaInfoUpdateDTO.getBindAddressInfo() || deviceMediaInfoUpdateDTO.getBindAddressInfo().isEmpty())) {
            batchParams.clear();
            for (DeviceMediaBindAddressDTO deviceMediaBindAddressDTO:deviceMediaInfoUpdateDTO.getBindAddressInfo()){
                DeviceMediaGatePO deviceMediaGatePO = new DeviceMediaGatePO();
                deviceMediaGatePO.setMediaId(deviceMediaInfoUpdateDTO.getMediaId());
                deviceMediaGatePO.setProjectId(deviceMediaInfoUpdateDTO.getProjectId());
                deviceMediaGatePO.setDeviceUnique(deviceMediaBindAddressDTO.getDeviceUnique());
                deviceMediaGatePO.setCreateTime(deviceMediaInfoPO.getUpdateTime());
                deviceMediaGatePO.setUpdateTime(deviceMediaInfoPO.getUpdateTime());
                deviceMediaGatePO.setStatus(DataStatusEnum.NORMAL.getType());
                batchParams.add(SqlUtil.durableData(deviceMediaGatePO, PlatformConstants.TABLE_SAVE));
            }
            intRes += iDeviceMediaGateDao.batchSave(batchParams);
        }

        iDeviceMediaPadFaceDao.removeUnibodyEntranceOne(deviceMediaInfoUpdateDTO.getMediaId());
        if (null != deviceMediaInfoUpdateDTO.getBindUnibodyEntranceInfo() && !deviceMediaInfoUpdateDTO.getBindUnibodyEntranceInfo().isEmpty()){
            // 批量保存多媒体资源-一体式人脸识别门禁设备关联信息
            batchParams.clear();
            Date saveTime = new Date();
            for (DeviceMediaBindPadFaceDTO deviceMediaBindPadFaceDTO:deviceMediaInfoUpdateDTO.getBindUnibodyEntranceInfo()){
                DeviceMediaEntrancePO deviceMediaEntrancePO = new DeviceMediaEntrancePO();
                deviceMediaEntrancePO.setMediaId(deviceMediaInfoPO.getMediaId());
                deviceMediaEntrancePO.setProjectId(deviceMediaInfoUpdateDTO.getProjectId());
                deviceMediaEntrancePO.setDeviceUnique(deviceMediaBindPadFaceDTO.getDeviceUnique());
                deviceMediaEntrancePO.setCreateTime(saveTime);
                deviceMediaEntrancePO.setUpdateTime(saveTime);
                deviceMediaEntrancePO.setStatus(DataStatusEnum.NORMAL.getType());
                batchParams.add(SqlUtil.durableData(deviceMediaEntrancePO,PlatformConstants.TABLE_SAVE));
            }
            intRes += iDeviceMediaGateDao.batchSaveEntrance(batchParams);
        }

        return intRes;
    }

    /**
     * <desc>
     *    将逗号分隔的源字符串转换为List.
     * </desc>
     *
     * @param sourceStr 逗号分隔的源字符串
     * @return String列表
     * @author Copy from LewisLouis by wangzhi
     * @createDate 2017-11-25
     */
    private List<String> castStrToListByCommaChar(String sourceStr){
        List<String> resultList;
        if (!StringUtils.isBlank(sourceStr)){
            resultList =  Arrays.asList(sourceStr.split(","));
        } else
        {
            resultList = new ArrayList<>();
        }
        return  resultList;
    }

    /**
     * <desc>
     *      发布多媒体资源，支持批量
     * </desc>
     *
     * @param mediaIds 多媒体资源id字符串
     * @return 影响的行数
     * @author wangzhi
     * @createDate 2018-04-09
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer publishMedias(String mediaIds) throws Exception {
        String[] mediaId = StringHandlerUtil.splitString(mediaIds);
        int intRes = iDeviceMediaInfoDao.publishMedias(mediaId, new Date());

        List<String> projectIds = iDeviceMediaInfoDao.getProjectIdsByMediaIds(Arrays.asList(mediaId));

        if (projectIds != null && !projectIds.isEmpty()) {
            // 发布状态变更，通知云对讲设备更新
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("projectId",projectIds.get(0));
            DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                    = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_MEDIA,jsonObject,projectIds.get(0));
            List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS = new ArrayList<>();
            deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
            JSONObject dataJs = new JSONObject();
            dataJs.put("data",deviceBusinessChangeLogPOS);
            messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                    JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);
            // 云门禁
            List<DeviceBusinessEntranceChangeLogPO> changeEntranceLogPOS = new ArrayList<>();
            changeEntranceLogPOS.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_MEDIA, jsonObject, projectIds.get(0)));
            JSONObject dataJsEntrance = new JSONObject();
            dataJsEntrance.put("data", changeEntranceLogPOS);
            //发送云门禁指令
            messageSender.send(
                    RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                    JSON.toJSONString(dataJsEntrance),
                    RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
            );
        }

        return intRes;
    }

    /**
     * <desc>
     *      修改已过期多媒体资源的发布状态和已发布多媒体资源发布状态
     * </desc>
     *
     * @return 是否修改成功
     * @author wangzhi
     * @createDate 2018-04-10
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean checkAndChangeOverMediaPublishStatusTask() throws Exception {
        Date nowTime = new Date();
        List<String> idListDisabled = iDeviceMediaInfoDao.getDisabledMediaIdList(nowTime);
        List<String> idListWillPublish = iDeviceMediaInfoDao.getWillPublishMediaIdList(nowTime);
        List<String> idList = new ArrayList<>();
        int intRes = 0;
        boolean isSuccess = false;
        if (null != idListDisabled && !idListDisabled.isEmpty()) {
            iDeviceMediaInfoDao.setPublishStatusBatch(idListDisabled);
            idList.addAll(idListDisabled);
            intRes++;
        }
        if (null != idListWillPublish && !idListWillPublish.isEmpty()){
            iDeviceMediaInfoDao.setWillPublishBatch(idListWillPublish);
            idList.addAll(idListWillPublish);
            intRes++;
        }
        if (intRes > 0) {
            isSuccess = true;
            List<String> projectIds = iDeviceMediaInfoDao.getProjectIdsByMediaIds(idList);
            for (String projectId:projectIds){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("projectId",projectId);
                DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                        = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_MEDIA,jsonObject,projectId);
                List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS = new ArrayList<>();
                deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
                JSONObject dataJs = new JSONObject();
                dataJs.put("data",deviceBusinessChangeLogPOS);
                messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                        JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);
                // 云门禁
                List<DeviceBusinessEntranceChangeLogPO> changeEntranceLogPOS = new ArrayList<>();
                changeEntranceLogPOS.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_MEDIA, jsonObject, projectId));
                JSONObject dataJsEntrance = new JSONObject();
                dataJsEntrance.put("data", changeEntranceLogPOS);
                //发送云门禁指令
                messageSender.send(
                        RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                        JSON.toJSONString(dataJsEntrance),
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
                );
            }
        }
        return isSuccess;
    }

    /**
     * <desc>
     *      兼容旧多媒体数据接口
     * </desc>
     *
     * @return
     * @author wangzhi
     * @createDate 2018-04-19
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer compatibilityOldMediaData() throws Exception {
        Date nowTime = new Date(); // 先获取当前时间
        int intRes = 0;
        List<Map<String,Object>> batchParams = new ArrayList<>();
        /*// 处理围墙机的旧数据兼容问题（围墙机旧数据属需求调整后正常，无需兼容）
        List<DeviceMediaWallForCompatibilityDTO> oldDeviceMediaWalls = iDeviceMediaWallDao.getOldDeviceMediaWall();
        if (null != oldDeviceMediaWalls || !oldDeviceMediaWalls.isEmpty()){
            iDeviceMediaWallDao.removeMediaWallByBuildIdNull();
            Map<String,Set<String>> compatibilityWallMap = new HashMap<>(); // 对于mediaId+projectId 对应的deviceUnique+sn去重
            for (DeviceMediaWallForCompatibilityDTO oldDeviceMediaWall:oldDeviceMediaWalls) {
                if (compatibilityWallMap.get(oldDeviceMediaWall.getMediaId() + "," + oldDeviceMediaWall.getProjectId()) == null){
                    Set<String> deviceUniqueSet = new HashSet<>();
                    deviceUniqueSet.add(oldDeviceMediaWall.getDeviceUnique() + "," + oldDeviceMediaWall.getSn());
                    compatibilityWallMap.put(oldDeviceMediaWall.getMediaId() + "," + oldDeviceMediaWall.getProjectId(),deviceUniqueSet);
                }else{
                    compatibilityWallMap.get(oldDeviceMediaWall.getMediaId() + "," + oldDeviceMediaWall.getProjectId()).add(oldDeviceMediaWall.getDeviceUnique() + "," + oldDeviceMediaWall.getSn());
                }
            }
            for(Map.Entry<String,Set<String>> entry:compatibilityWallMap.entrySet()){
                String[] mediaIdAndProjectId = StringHandlerUtil.splitString(entry.getKey());
                for (String deviceUniqueAndSnFromSet:entry.getValue()){
                    String[] deviceUniqueAndSn = StringHandlerUtil.splitString(deviceUniqueAndSnFromSet);
                    List<String> buildIds = iDeviceMediaWallDao.getAllIntercomBuildIdByDeviceUnique(deviceUniqueAndSn[0]);
                    for (String buildId:buildIds) {
                        DeviceMediaWallPO deviceMediaWallPO = new DeviceMediaWallPO();
                        deviceMediaWallPO.setMediaId(mediaIdAndProjectId[0]);
                        deviceMediaWallPO.setProjectId(mediaIdAndProjectId[1]);
                        deviceMediaWallPO.setDeviceUnique(deviceUniqueAndSn[0]);
                        deviceMediaWallPO.setSn(deviceUniqueAndSn[1]);
                        deviceMediaWallPO.setStatus(DataStatusEnum.NORMAL.getType());
                        // 存入该设备序列号的所有楼栋id
                        deviceMediaWallPO.setBuildId(buildId);
                        deviceMediaWallPO.setCreateTime(nowTime);
                        deviceMediaWallPO.setUpdateTime(nowTime);
                        batchParams.add(SqlUtil.durableData(deviceMediaWallPO, PlatformConstants.TABLE_SAVE));
                    }
                }
            }
            //保存围墙机关联信息
            intRes += iDeviceMediaWallDao.batchSave(batchParams);
        }*/

        // 处理门口机的旧数据兼容问题，兼容思路：将和地址的对应关系转换成和设备的对应关系
        List<DeviceMediaGateForCompatibilityDTO> oldDeviceMediaGates = iDeviceMediaGateDao.getOldDeviceMediaGate();
        if (null != oldDeviceMediaGates || !oldDeviceMediaGates.isEmpty()){
//            batchParams.clear();
            iDeviceMediaGateDao.removeMediaGateByDeviceUniqueNull();
            Map<String,Set<String>> compatibilityGateAddressMap = new HashMap<>(); // 对于mediaId+projectId 对应的buildId+unitId去重
            Map<String,Set<String>> compatibilityGateDeviceUniqueMap = new HashMap<>(); // 对于mediaId+projectId 对应的deviceUnique去重
            for (DeviceMediaGateForCompatibilityDTO oldDeviceMediaGate:oldDeviceMediaGates) {
                if (compatibilityGateAddressMap.get(oldDeviceMediaGate.getMediaId() + "," + oldDeviceMediaGate.getProjectId()) == null){
                    Set<String> buildIdAndUnitIdSet = new HashSet<>();
                    buildIdAndUnitIdSet.add(oldDeviceMediaGate.getBuildId() + "," + oldDeviceMediaGate.getUnitId());
                    compatibilityGateAddressMap.put(oldDeviceMediaGate.getMediaId() + "," + oldDeviceMediaGate.getProjectId(),buildIdAndUnitIdSet);
                }else{
                    compatibilityGateAddressMap.get(oldDeviceMediaGate.getMediaId() + "," + oldDeviceMediaGate.getProjectId()).add(oldDeviceMediaGate.getBuildId() + "," + oldDeviceMediaGate.getUnitId());
                }
            }
            // 将和地址的对应关系转换成和设备的对应关系
            for (Map.Entry<String,Set<String>> entry:compatibilityGateAddressMap.entrySet()){
//                String[] mediaIdAndProjectId = StringHandlerUtil.splitString(entry.getKey());
                for (String buildIdAndUnitIdFromSet:entry.getValue()){
                    String[] buildIdAndUnitId = StringHandlerUtil.splitString(buildIdAndUnitIdFromSet);
                    // 使用buildId和unitId获取云对讲设备的deviceUnique
                    List<String> deviceUniques = iDeviceMediaGateDao.getAllIntercomDeviceUniqueByAddress(buildIdAndUnitId[0], buildIdAndUnitId[1]);
                    for(String deviceUnique:deviceUniques){
                        if (compatibilityGateDeviceUniqueMap.get(entry.getKey()) == null){
                            Set<String> deviceUniqueSet = new HashSet<>();
                            deviceUniqueSet.add(deviceUnique);
                            compatibilityGateDeviceUniqueMap.put(entry.getKey(),deviceUniqueSet);
                        }else {
                            compatibilityGateDeviceUniqueMap.get(entry.getKey()).add(deviceUnique);
                        }
                    }
                }
            }
            for (Map.Entry<String,Set<String>> entry:compatibilityGateDeviceUniqueMap.entrySet()){
                String[] mediaIdAndProjectId = StringHandlerUtil.splitString(entry.getKey());
                for (String deviceUnique:entry.getValue()){
                    DeviceMediaGatePO deviceMediaGatePO = new DeviceMediaGatePO();
                    deviceMediaGatePO.setMediaId(mediaIdAndProjectId[0]);
                    deviceMediaGatePO.setProjectId(mediaIdAndProjectId[1]);
                    // 存入该地址的设备序列号
                    deviceMediaGatePO.setDeviceUnique(deviceUnique);
//                        deviceMediaGatePO.setBuildId(buildIdAndUnitId[0]);
//                        deviceMediaGatePO.setUnitId(buildIdAndUnitId[1]);
                    deviceMediaGatePO.setStatus(DataStatusEnum.NORMAL.getType());
                    deviceMediaGatePO.setCreateTime(nowTime);
                    deviceMediaGatePO.setUpdateTime(nowTime);
                    batchParams.add(SqlUtil.durableData(deviceMediaGatePO, PlatformConstants.TABLE_SAVE));
                }
            }
            // 保存门口机关联信息
            if (batchParams != null && !batchParams.isEmpty()) {
                intRes +=  iDeviceMediaGateDao.batchSave(batchParams);
            }
        }

        // 兼容旧多媒体资源发布状态,查询所有投放时间为空的多媒体资源
        List<DeviceMediaInfoPO> deviceMediaInfoForUpdate = new ArrayList<>();
        List<DeviceMediaInfoPO> deviceMediaInfoPOs = iDeviceMediaInfoDao.getAllMediaInfoByPutTimeNull();
        // 处理发布状态逻辑
        if (deviceMediaInfoPOs != null && !deviceMediaInfoPOs.isEmpty()) {
            for (DeviceMediaInfoPO deviceMediaInfoPO:deviceMediaInfoPOs) {
                if (deviceMediaInfoPO.getStatus() == 1){ // 启用的多媒体资源处理
                    DeviceMediaInfoPO enableMedia = new DeviceMediaInfoPO();
                    BeanUtils.copyProperties(deviceMediaInfoPO,enableMedia);
                    enableMedia.setPublishStatus(1); // 发布状态设置为已发布
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(enableMedia.getCreateTime());
                    calendar.add(Calendar.YEAR,5);
                    enableMedia.setPutStartTime(enableMedia.getCreateTime());
                    enableMedia.setPutEndTime(calendar.getTime());
                    enableMedia.setUpdateTime(nowTime);
                    deviceMediaInfoForUpdate.add(enableMedia);
                }
                if (deviceMediaInfoPO.getStatus() == 2){ // 禁用的多媒体资源处理
                    DeviceMediaInfoPO forbiddenMedia = new DeviceMediaInfoPO();
                    BeanUtils.copyProperties(deviceMediaInfoPO,forbiddenMedia);
                    forbiddenMedia.setPublishStatus(0); // 发布状态设置为已过期
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(nowTime);
                    calendar.add(Calendar.DATE,-1);
                    forbiddenMedia.setPutStartTime(forbiddenMedia.getCreateTime());
                    forbiddenMedia.setPutEndTime(calendar.getTime());
                    forbiddenMedia.setUpdateTime(nowTime);
                    deviceMediaInfoForUpdate.add(forbiddenMedia);
                }
            }
        }
        // 批量更新旧多媒体资源发布状态
        if (deviceMediaInfoForUpdate != null && !deviceMediaInfoForUpdate.isEmpty()) {
            intRes += iDeviceMediaInfoDao.batchUpdatePutTimeAndPublishStatus(SqlUtil.durableDataList(deviceMediaInfoForUpdate, PlatformConstants.TABLE_UPDATE));
        }

        return intRes;
    }


    /**
     * <desc>
     *      修复本人因失误造成的错误数据，同时兼容旧多媒体资源的发布状态
     *      PS:已作废，不再使用
     * </desc>
     *
     * @return
     * @author wangzhi
     * @createDate 2018-04-20
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer repairWrongData() throws Exception {
        // 处理门口机错误数据
        // 先查出所有门口机错误数据
        Date nowTime = new Date(); // 先获取当前时间
        int intRes = 0;
        List<DeviceMediaGatePO> allWrongGateDatas = iDeviceMediaGateDao.getAllWrongGateData();
        if (allWrongGateDatas != null && !allWrongGateDatas.isEmpty()){
            // 修复门口机错误数据
            Map<String,Set<String>> repairGateMap = new HashMap<>(); // 用于存放每个mediaId对应的deviceUnique
            List<Integer> gateIds = new ArrayList<>(); // 用于存放被查出来处理的错误数据的id，进行批量删除
            // 存放每个mediaId+projectId和其对应deviceUnique
            for (DeviceMediaGatePO deviceMediaGatePO:allWrongGateDatas) {
                if (repairGateMap.get(deviceMediaGatePO.getMediaId() + "," + deviceMediaGatePO.getProjectId()) == null){
                    Set<String> deviceUniqueSet = new HashSet<>(); // set保证去重
                    deviceUniqueSet.add(deviceMediaGatePO.getDeviceUnique());
                    repairGateMap.put(deviceMediaGatePO.getMediaId() + "," + deviceMediaGatePO.getProjectId(),deviceUniqueSet);
                }else{
                    repairGateMap.get(deviceMediaGatePO.getMediaId() + "," + deviceMediaGatePO.getProjectId()).add(deviceMediaGatePO.getDeviceUnique());
                }
                gateIds.add(deviceMediaGatePO.getId()); // 将id存入待删除集合
            }
            // 还原门口机数据
            List<Map<String,Object>> batchParams = new ArrayList<>(); // 保存还原的门口机数据
            Set<String> device = new HashSet<>();
            for (Map.Entry<String,Set<String>> entry:repairGateMap.entrySet()) {
                String[] strings = StringHandlerUtil.splitString(entry.getKey());
                for (String deviceUnique:entry.getValue()){
                    List<DeviceCloudIntercomBridgeInfoPO> addresses = iDeviceCloudIntercomBridgeInfoDao.getAddress(deviceUnique);
                        ab:for (DeviceCloudIntercomBridgeInfoPO address:addresses) {
                            if(device.add(deviceUnique)) {
                                DeviceMediaGatePO deviceMediaGatePO = new DeviceMediaGatePO();
                                deviceMediaGatePO.setMediaId(strings[0]);
                                deviceMediaGatePO.setProjectId(strings[1]);
                                deviceMediaGatePO.setDeviceUnique(deviceUnique);
                                deviceMediaGatePO.setStatus(5);
                                deviceMediaGatePO.setCreateTime(nowTime);
                                deviceMediaGatePO.setUpdateTime(nowTime);
                                deviceMediaGatePO.setBuildId(address.getBuildId());
                                deviceMediaGatePO.setUnitId(address.getUnitId());
                                batchParams.add(SqlUtil.durableData(deviceMediaGatePO, PlatformConstants.TABLE_SAVE));
                            }else{
                                break ab;
                            }
                    }
                }
            }
            intRes += iDeviceMediaGateDao.batchSave(batchParams);
            // 物理删除门口机错误数据
            intRes += iDeviceMediaGateDao.removeWrongGateData(gateIds);
        }

//        // 处理围墙机错误数据
//        // 先查出所有围墙机错误数据
//        List<DeviceMediaWallPO> allWrongWallDatas = iDeviceMediaWallDao.getAllWrongWallData();
//        if (allWrongWallDatas != null && !allWrongWallDatas.isEmpty()){
//            // 修复围墙机错误数据
//            Map<String,Set<String>> repairWallMap = new HashMap<>();
//            List<Integer> wallIds = new ArrayList<>();
//            for (DeviceMediaWallPO deviceMediaWallPO:allWrongWallDatas) {
//                if (repairWallMap.get(deviceMediaWallPO.getMediaId() + "," + deviceMediaWallPO.getProjectId()) == null){
//                    Set<String> deviceUniqueSet = new HashSet<>();
//                    deviceUniqueSet.add(deviceMediaWallPO.getDeviceUnique() + "," + deviceMediaWallPO.getSn());
//                    repairWallMap.put(deviceMediaWallPO.getMediaId() + "," + deviceMediaWallPO.getProjectId(),deviceUniqueSet);
//                }else{
//                    repairWallMap.get(deviceMediaWallPO.getMediaId() + "," + deviceMediaWallPO.getProjectId()).add(deviceMediaWallPO.getDeviceUnique() + "," + deviceMediaWallPO.getSn());
//                }
//                wallIds.add(deviceMediaWallPO.getId());
//            }
//            // 还原围墙机数据
//            List<Map<String,Object>> batchParams = new ArrayList<>(); // 保存还原的门口机数据
//            for (Map.Entry<String,Set<String>> entry:repairWallMap.entrySet()) {
//                String[] strings = StringHandlerUtil.splitString(entry.getKey());
//                for (String deviceUniqueAndSn:entry.getValue()){
//                    String[] strings1 = StringHandlerUtil.splitString(deviceUniqueAndSn);
//                    List<DeviceCloudIntercomBridgeInfoPO> addresses = iDeviceCloudIntercomBridgeInfoDao.getAddress(strings1[0]);
//                    for (DeviceCloudIntercomBridgeInfoPO address:addresses) {
//                        DeviceMediaWallPO deviceMediaWallPO = new DeviceMediaWallPO();
//                        deviceMediaWallPO.setMediaId(strings[0]);
//                        deviceMediaWallPO.setProjectId(strings[1]);
//                        deviceMediaWallPO.setDeviceUnique(strings1[0]);
//                        deviceMediaWallPO.setStatus(5);
//                        deviceMediaWallPO.setCreateTime(nowTime);
//                        deviceMediaWallPO.setUpdateTime(nowTime);
//                        deviceMediaWallPO.setBuildId(address.getBuildId());
//                        deviceMediaWallPO.setSn(strings1[1]);
//                        batchParams.add(SqlUtil.durableData(deviceMediaWallPO, PlatformConstants.TABLE_SAVE));
//                    }
//                }
//            }
//            intRes += iDeviceMediaWallDao.batchSave(batchParams);
//
//            // 物理删除围墙机错误数据
//            intRes += iDeviceMediaWallDao.removeWrongWallData(wallIds);
//        }
//
//        // 兼容旧多媒体资源发布状态,查询所有投放时间为空的多媒体资源
//        List<DeviceMediaInfoPO> deviceMediaInfoForUpdate = new ArrayList<>();
//        List<DeviceMediaInfoPO> deviceMediaInfoPOs = iDeviceMediaInfoDao.getAllMediaInfoByPutTimeNull();
//        // 处理发布状态逻辑
//        if (deviceMediaInfoPOs != null && !deviceMediaInfoPOs.isEmpty()) {
//            for (DeviceMediaInfoPO deviceMediaInfoPO:deviceMediaInfoPOs) {
//                if (deviceMediaInfoPO.getStatus() == 1){ // 启用的多媒体资源处理
//                    DeviceMediaInfoPO enableMedia = new DeviceMediaInfoPO();
//                    BeanUtils.copyProperties(deviceMediaInfoPO,enableMedia);
//                    enableMedia.setPublishStatus(1); // 发布状态设置为已发布
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.setTime(enableMedia.getCreateTime());
//                    calendar.add(Calendar.YEAR,5);
//                    enableMedia.setPutStartTime(enableMedia.getCreateTime());
//                    enableMedia.setPutEndTime(calendar.getTime());
//                    enableMedia.setUpdateTime(nowTime);
//                    deviceMediaInfoForUpdate.add(enableMedia);
//                }
//                if (deviceMediaInfoPO.getStatus() == 2){ // 禁用的多媒体资源处理
//                    DeviceMediaInfoPO forbiddenMedia = new DeviceMediaInfoPO();
//                    BeanUtils.copyProperties(deviceMediaInfoPO,forbiddenMedia);
//                    forbiddenMedia.setPublishStatus(0); // 发布状态设置为已过期
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.setTime(nowTime);
//                    calendar.add(Calendar.DATE,-1);
//                    forbiddenMedia.setPutStartTime(forbiddenMedia.getCreateTime());
//                    forbiddenMedia.setPutEndTime(calendar.getTime());
//                    forbiddenMedia.setUpdateTime(nowTime);
//                    deviceMediaInfoForUpdate.add(forbiddenMedia);
//                }
//            }
//        }
//        // 批量更新旧多媒体资源发布状态
//        if (deviceMediaInfoForUpdate != null && !deviceMediaInfoForUpdate.isEmpty()) {
//            intRes += iDeviceMediaInfoDao.batchUpdatePutTimeAndPublishStatus(SqlUtil.durableDataList(deviceMediaInfoForUpdate, PlatformConstants.TABLE_UPDATE));
//        }

        return intRes;
    }

    /**
     * <desc>
     *      设备广告审核通过
     * </desc>
     *
     * @param deviceMediaSetEnableDTO 设备广告参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/12/25
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer audit(DeviceMediaSetEnableDTO deviceMediaSetEnableDTO) throws Exception {

        Date nowTime = new Date();
        Map<String, Object> params = new HashMap<>();
        SimpleDateFormat dateFormat =new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        DeviceMediaInfoVO mediaInfoVO = iDeviceMediaInfoDao.getOneMediaInfo(deviceMediaSetEnableDTO.getMediaId());
        int publishStatus = 0;
        if (mediaInfoVO == null){
            return 1;
        }
        if (DataStatusEnum.NORMAL.getType().toString().equals(deviceMediaSetEnableDTO.getAuditStatus())){
            //发布日期之前，状态置为未发布
            if (nowTime.before(dateFormat.parse(mediaInfoVO.getPutStartTime()))){
                publishStatus = DeviceMediaInfoPublishStatusEnum.UNPUBLISHED.getType();
            }
            //发布日期之后，状态置为已过期
            if (nowTime.after(dateFormat.parse(mediaInfoVO.getPutEndTime()))){
                publishStatus =  DeviceMediaInfoPublishStatusEnum.OUT_OF_DATE.getType();
            }
            //发布日期之中，状态置为已发布
            if (nowTime.after(dateFormat.parse(mediaInfoVO.getPutStartTime())) && nowTime.before(dateFormat.parse(mediaInfoVO.getPutEndTime()))){
                publishStatus = DeviceMediaInfoPublishStatusEnum.PUBLISHED.getType();
            }
        }else{
            publishStatus = DeviceMediaInfoPublishStatusEnum.UN_PASSES.getType();
        }

        params.put("mediaId", mediaInfoVO.getMediaId());
        params.put("updateTime", nowTime);
        params.put("publishStatus", publishStatus);
        params.put("remark", deviceMediaSetEnableDTO.getRemark());
        iDeviceMediaInfoDao.audit(params);

        //通知云对讲
        if (NumberHandlerUtil.isEqual(mediaInfoVO.getStatus(), DataStatusEnum.NORMAL.getType()) &&
                NumberHandlerUtil.isEqual(publishStatus, DeviceMediaInfoPublishStatusEnum.PUBLISHED.getType())) {
            if (NumberHandlerUtil.isEqual(mediaInfoVO.getEquipType(), PropertyEquipTypeEnum.CLOUD_INTERCOM.getType())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("projectId", mediaInfoVO.getProjectId());
                DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                        = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_MEDIA, jsonObject, mediaInfoVO.getProjectId());
                List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS = new ArrayList<>();
                deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
                JSONObject dataJs = new JSONObject();
                dataJs.put("data", deviceBusinessChangeLogPOS);
                messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                        JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);
            }
            if (NumberHandlerUtil.isEqual(mediaInfoVO.getEquipType(), PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("projectId", mediaInfoVO.getProjectId());
                // 云门禁
                List<DeviceBusinessEntranceChangeLogPO> changeEntranceLogPOS = new ArrayList<>();
                changeEntranceLogPOS.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_MEDIA, jsonObject, mediaInfoVO.getProjectId()));
                JSONObject dataJs = new JSONObject();
                dataJs.put("data", changeEntranceLogPOS);
                //发送云门禁指令
                messageSender.send(
                        RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                        JSON.toJSONString(dataJs),
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
                );
            }
        }
        return 1;
    }

}
